#include "UserInfo.h"

#include "WordLib.h"
#include "_Global/GlobalClass.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QCryptographicHash>

bool StudyInfo::loadClassInfoLocal(QSqlDatabase* db)
{
    if(db == nullptr)return false;
    if (!db->isValid() || !db->isOpen())
        return false;

    QString sql = "SELECT * FROM ClassInfo";
    QSqlQuery query(*db);  //查询


    if(!query.exec(sql))
    {
        Critical("Query ClassInfo Error");
        Critical(db->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return false;
    }

    //query.size();
    //query.seek(0);

    qDebug()<<"读取ClassInfo:";
    while(query.next())
    {
        ClassInfo *cInfo = new ClassInfo;
        cInfo->m_nClassID = query.value("ID").toInt();
        cInfo->m_unClassLevelCount = query.value("LevelCount").toInt();
        cInfo->m_strClassName = query.value("Name").toString();
        m_mapClassInfo.insert(query.value("ID").toString(),QVariant::fromValue<ClassInfo*>(cInfo));

        qDebug()<<"ClassID:"<<cInfo->m_nClassID<<":"<<cInfo->m_strClassName;
    }
    qDebug()<<"共"<<m_mapClassInfo.count();
    qDebug()<<"------------------";
    query.finish();

    return true;
}

bool StudyInfo::loadStudyInfoLocal(QSqlDatabase* db,quint32 usergameid)
{
    if(db == nullptr)return false;
    if (!db->isValid() || !db->isOpen())
        return false;

    QString sql;
    QSqlQuery query(*db);  //查询

    //a.先读取ClassInfo
    bool bRet = loadClassInfoLocal(db);
    if(!bRet)
        return false;

    //b.读取记录
    sql = QString("SELECT * FROM GameUserClassRecord WHERE usergameid=%1 ORDER BY ClassID,LevelID").arg(usergameid);
    if(!query.exec(sql))
    {
        Critical("Query ClassInfo Error");
        Critical(db->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return false;
    }

    //query.seek(0);


    QString cID;
    int n = 0;

    qDebug()<<"读取levelInfo:";
    while(query.next())
    {
        cID = query.value("ClassID").toString();
        if(m_mapClassInfo.contains(cID))
        {
            LevelInfo *pLevel = new LevelInfo;
            pLevel->m_nClassID = query.value("ClassID").toInt();
            pLevel->m_nLevelID = query.value("LevelID").toInt();
            pLevel->m_unWordCount = query.value("WordCount").toInt();
            //pLevel->m_CorrectCount = query.value("CorrectCount").toInt();
            //pLevel->m_MistakeCount = query.value("MistakeCount").toInt();
            pLevel->m_strWordRecords = query.value("WordRecords").toString();
            m_mapClassInfo.value(cID).value<ClassInfo*>()->m_mapLevel.insert(QString::number(pLevel->m_nLevelID), QVariant::fromValue(pLevel));

            //qDebug()<<"Level:"<<pLevel->m_nLevelID<<":"<<pLevel->m_unWordCount
            //       <<":"<<pLevel->m_strWordRecords;
        }
        else
            qDebug()<<"存在错误ClassID的levelInfo:"<<query.value("id").toInt();
        n++;
    }

    qDebug()<<"共:"<<n;
    qDebug()<<"------------------";

    query.finish();
    return true;
}


bool StudyInfo::saveResultLocal(QSqlDatabase* db, WordLib* m_pWordLib, quint32 usergameid)
{
    if(db == nullptr)return false;
    if (!db->isValid() || !db->isOpen())
        return false;

    ClassInfo *pCInfo;
    pCInfo = m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>();

    QSqlQuery query(*db);  //查询
    QString sql;
    if(pCInfo->m_mapLevel.count() <= m_pWordLib->m_nLevelID)     //第一关有这种情况，新插入记录
    {
        sql = QString("INSERT INTO GameUserClassRecord(usergameid,ClassID,LevelID,WordCount,WordRecords) VALUES(%1,%2,%3,%4,'%5')").arg(usergameid).arg(m_pWordLib->m_nClassID).arg(m_pWordLib->m_nLevelID).arg(m_pWordLib->wordCount()).arg(m_pWordLib->m_strResult);
        if(!query.exec(sql))
        {
            Critical("Query Saved Error");
            Critical(m_pWordLib->getDB()->lastError().text());
            Critical(query.lastError().text());
            Critical(sql);
            query.finish();
            return false;
        }
        query.finish();

        LevelInfo *pLevel = new LevelInfo;
        pLevel->m_nClassID = m_pWordLib->m_nClassID;
        pLevel->m_nLevelID = m_pWordLib->m_nLevelID;
        pLevel->m_unWordCount = m_pWordLib->wordCount();
        //pLevel->m_CorrectCount = query.value("CorrectCount").toInt();
        //pLevel->m_MistakeCount = query.value("MistakeCount").toInt();
        pLevel->m_strWordRecords = m_pWordLib->m_strResult;
        m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.insert(QString::number(pLevel->m_nLevelID), QVariant::fromValue(pLevel));

    }
    else    //更新记录
    {
        sql = QString("UPDATE GameUserClassRecord SET WordRecords='%1' WHERE usergameid=%2 AND ClassID=%3 AND LevelID=%4").arg(m_pWordLib->m_strResult).arg(usergameid).arg(m_pWordLib->m_nClassID).arg(m_pWordLib->m_nLevelID);
        if(!query.exec(sql))
        {
            Critical("Query Saved Error");
            Critical(m_pWordLib->getDB()->lastError().text());
            Critical(query.lastError().text());
            Critical(sql);
            query.finish();
            return false;
        }
        query.finish();

        m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.value(QString::number(m_pWordLib->m_nLevelID)).value<LevelInfo*>()->m_strWordRecords = m_pWordLib->m_strResult;
    }

    /*
    m_db.transaction();
    query.prepare("INSERT INTO GameUserClassRecord(ClassID,LevelID,WordRecords) VALUES(:Word,:Phonetic,:Explain)");
    query.bindValue(":Word",ExcelQuery.value("Word").toString());
    query.bindValue(":Phonetic",ExcelQuery.value("Phonetic").toString());
    query.bindValue(":Explain",ExcelQuery.value("Explain").toString());
    query.exec();
    query.finish();
    m_db.commit();
    */

    //如果学完，且下一关没开启
    if(m_pWordLib->unStudiedCount() == 0 && pCInfo->m_mapLevel.count() == m_pWordLib->m_nLevelID + 1)
    {
        int wordCount = m_pWordLib->getWordCount(m_pWordLib->m_nClassID, m_pWordLib->m_nLevelID + 1);
        if(wordCount > 0)   //下一关有单词
        {
            sql = QString("INSERT INTO GameUserClassRecord(usergameid,ClassID,LevelID,WordCount,WordRecords) VALUES(%1,%2,%3,%4,'')").arg(usergameid).arg(m_pWordLib->m_nClassID).arg(m_pWordLib->m_nLevelID + 1).arg(wordCount);
            if(!query.exec(sql))
            {
                Critical("Query Saved Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                return false;
            }
            query.finish();

            LevelInfo *pLevel = new LevelInfo;
            pLevel->m_nClassID = m_pWordLib->m_nClassID;
            pLevel->m_nLevelID = m_pWordLib->m_nLevelID + 1;
            pLevel->m_unWordCount = wordCount;
            pLevel->m_strWordRecords = "";
            m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>()->m_mapLevel.insert(QString::number(pLevel->m_nLevelID), QVariant::fromValue(pLevel));
        }
    }

    return true;
}


bool UserInfo::checkBadWord(QString word)
{
    if(m_pWordLib == nullptr)return false;
    if (!m_pWordLib->isValid())
        return false;

    QString sql = QString("SELECT * FROM LMS_BadWords WHERE '%1' LIKE '%'||BadWord||'%'").arg(word);
    QSqlQuery query(*m_pWordLib->getDB());  //查询

    if(!query.exec(sql))
    {
        qCritical() << ("Query BadWord Error");
        qCritical() << (m_pWordLib->getDB()->lastError().text());
        qCritical() << (query.lastError().text());
        qCritical() << (sql);
        query.finish();
        return false;
    }

    //qDebug() << "query:" << sql;// << query.size();
    if(query.next())
    {
        qDebug() << "badWord:" << query.value("BadWord");
        query.finish();
        return false;
    }

    query.finish();
    return true;
}

bool UserInfo::sl_qml_ChoiceGameServer(int gameServerID)
{
    if(m_mapGameServerInfo.count() == 0)
    {
        emit s_choiceGameServerStatus(-1);
        qDebug()<<"[!UserInfo]登录游戏服务器出错！";
        return false;
    }

    m_unGameServerId = gameServerID;
    _GameServerInfo *pGameServerInfo = m_mapGameServerInfo.value(QString::number(m_unGameServerId), QVariant::fromValue(nullptr))
            .value<_GameServerInfo*>();
    //((_GameServerInfo*)(m_mapGameServerInfo.value(m_unGameServerId)));

    if(pGameServerInfo == nullptr)
    {
        qDebug()<<"[!UserInfo]选择游戏服务器出错！";
        return false;
    }

    //本地!!!???
    if(pGameServerInfo->m_strIP == "local")
    {
        int ret = loadGameUserInfoLocal();
        if(ret == 1)
        {
            emit s_choiceGameServerStatus(1);
            return true;
        }
        else if(ret == 0)
        {
            emit s_choiceGameServerStatus(0);
            return true;
        }
        else
        {
            emit s_choiceGameServerStatus(-1);
            qDebug()<<"登录游戏服务器出错！";
            return false;     //本地读取游戏用户信息
        }
    }
    else
    {
        m_pGameSocket->m_strIP = pGameServerInfo->m_strIP;
        m_pGameSocket->m_unPort = pGameServerInfo->m_unPort;

        m_pGameSocket->connectServer();

        loadGameUserInfo();
        return true;
        //这里是网络读取代码
    }
}

int UserInfo::loadGameUserInfo()
{
    _GameServerInfo* pGameServerInfo = m_mapGameServerInfo.value(QString::number(m_unGameServerId),QVariant::fromValue(nullptr))
            .value<_GameServerInfo*>();

    if(pGameServerInfo == nullptr)
        return false;

    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                << (qint16)GAME_SERVER_GAMEUSERINFO
                                << m_LoginInfo.m_unID
                                << serverID()
                                << m_LoginInfo.m_unGradeID
                                << pGameServerInfo->m_strKey
                                << m_LoginInfo.m_nClientType
                                   ;
    m_pGameSocket->send(true);

    qDebug()<<"[loadGameUserInfo]获取GameUserInfo中..."<<m_LoginInfo.m_unGradeID;
    return 0;

    //setFlagCorrectAnswer(false);
    //setCanReview(false);


    //m_StudyInfo.loadStudyInfo(m_pTempDB,userGameID());
}

int UserInfo::loadGameUserInfoLocal()
{
    if(m_pTempDB == nullptr)return -1;
    if (!m_pTempDB->isValid() || !m_pTempDB->isOpen())
        return -1;

    QSqlQuery query(*m_pTempDB);  //查询

    QString sql;


    //检查GameUserInfo
    sql = QString("SELECT * FROM GameUserInfo WHERE userid=%1 AND serverid=%2").arg(m_LoginInfo.m_unID).arg(serverID());

    if(!query.exec(sql))
    {
        Critical("Query GameUserInfo error");
        Critical(m_pWordLib->getDB()->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return -2;
    }

    if(query.next())
    {
        m_GameServerUserInfo.unUserGameID = query.value("ID").toInt();
        setNickName(query.value("NickName").toString());
        setSex(query.value("Sex").toInt());
        setScoreCount(query.value("Score").toInt());
        //m_GameServerUserInfo.items.canReview = query.value("").to;
        //m_GameServerUserInfo.items.flagCorrectAnswer = query.value("").to;
        query.finish();
    }
    else
    {
        qDebug()<<"登录GameServer:没有此GameUserInfo:"<<m_LoginInfo.m_unID<<serverID();
        query.finish();
        return 0;
    }

/*
    //读取经验
    sql = QString("SELECT * FROM GameUserScoreInfo WHERE usergameid=%1").arg(userGameID());

    if(!query.exec(sql))
    {
        Critical("Query ClassInfo Error");
        return -1;
    }

    if(query.next())
    {
        setScoreCount(query.value("score").toInt());
    }
    else
    {
        qDebug()<<"Err：读取经验错误！";
        setScoreCount(0);
    }
    query.finish();
*/

    setFlagCorrectAnswer(false);
    setCanReview(false);


    m_StudyInfo.loadStudyInfoLocal(m_pTempDB,userGameID());
    return 1;
}



bool UserInfo::loadGameServersInfoLocal()
{
    if(m_pTempDB == nullptr)return false;
    if (!m_pTempDB->isValid() || !m_pTempDB->isOpen())
        return false;

    clearGameServersInfo();

    QSqlQuery query(*m_pTempDB);  //查询

    QString sql;
    sql = QString("SELECT * FROM ServerInfo");

    if(!query.exec(sql))
    {
        Critical("Query ServerInfo Error");
        Critical(m_pWordLib->getDB()->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return false;
    }

    while(query.next())
    {
        _GameServerInfo *pGameInfo = new _GameServerInfo;
        pGameInfo->m_unServerID = query.value("ID").toInt();
        pGameInfo->m_strName = query.value("Name").toString();
        pGameInfo->m_strIP = query.value("IP").toString();
        pGameInfo->m_unPort = query.value("Port").toInt();
        pGameInfo->m_strKey = query.value("Key").toString();
        m_mapGameServerInfo.insert(QString::number(pGameInfo->m_unServerID), QVariant::fromValue(pGameInfo));
        //m_GameServerInfoList.append(QVariant::fromValue<_GameServerInfo*>(pGameInfo));
        //m_GameServerInfoList.insert(query.value("ID").toString(),QVariant::fromValue<ClassInfo*>(cInfo));
    }
    query.finish();

    return true;
}

bool UserInfo::updateGameUserScoreInfoLocal()
{
    if(m_pTempDB == nullptr)return false;
    if (!m_pTempDB->isValid() || !m_pTempDB->isOpen())
        return false;

    QSqlQuery query(*m_pTempDB);  //查询

    QString sql;


    sql = QString("INSERT INTO GameUserScoreRecord(usergameid,ScoreAdd) VALUES(%1,%2)").arg(userGameID()).arg(m_GameServerUserInfo.nScoreAdd);
    if(!query.exec(sql))
    {
        Critical("Query ClassInfo Error");
        Critical(m_pWordLib->getDB()->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return false;
    }
    query.finish();

    updateScoreCount();

    sql = QString("UPDATE GameUserInfo SET Score=%1 WHERE ID=%2").arg(scoreCount()).arg(userGameID());
    if(!query.exec(sql))
    {
        Critical("Query ClassInfo Error");
        Critical(m_pWordLib->getDB()->lastError().text());
        Critical(query.lastError().text());
        Critical(sql);
        query.finish();
        return false;
    }

    query.finish();
    return true;

}

bool UserInfo::saveResult(WordLib* m_pWordLib)
{
    //保存结果
    //qDebug() << "!!!saveResult:" << m_pWordLib->m_nClassID << m_pWordLib->m_nLevelID;
    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)GAME_SERVER_REQUEST
        << (qint16)GAME_SERVER_SAVESTUDYINFO
        //<< userGameID()
        //<< (qint16)m_pWordLib->m_nType
        << (quint32)m_pWordLib->m_nClassID
        << (quint32)m_pWordLib->m_nLevelID
        //<< (quint32)m_pWordLib->wordCount()
        << m_pWordLib->m_strResult;
    emit s_SendCodeDataToServer(m_pGameSocket,ba);
    if(saveClassLevel(m_pWordLib->m_nClassID, m_pWordLib->m_nLevelID, m_pWordLib->m_strResult) == false)
        return false;
    /*
    m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                << (qint16)GAME_SERVER_SAVESTUDYINFO
                                //<< userGameID()
                                << (quint32)m_pWordLib->m_nClassID
                                << (quint32)m_pWordLib->m_nLevelID
                                << (quint32)m_pWordLib->wordCount()
                                << m_pWordLib->m_strResult
                                << false;
    m_pGameSocket->send();*/

    ClassInfo *pCInfo;
    pCInfo = m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(m_pWordLib->m_nClassID)).value<ClassInfo*>();

    //如果学完，且下一关没开启
    if(m_pWordLib->unStudiedCount() == 0  //本关学完
            && pCInfo->m_mapLevel.count() == m_pWordLib->m_nLevelID + 1  //下一关没开
            && pCInfo->m_mapLevel.count() < (int)pCInfo->m_unClassLevelCount       //有下一关
            )
    {
        int wordCount = m_pWordLib->getWordCount(m_pWordLib->m_nClassID, m_pWordLib->m_nLevelID + 1);
        if(wordCount > 0)   //下一关有单词
        {
            QByteArray ba;
            QDataStream out(&ba,QIODevice::WriteOnly);
            out << (qint16)GAME_SERVER_REQUEST
                << (qint16)GAME_SERVER_SAVESTUDYINFO
                //<< userGameID()
                //<< (qint16)m_pWordLib->m_nType
                << (quint32)m_pWordLib->m_nClassID
                << (quint32)(m_pWordLib->m_nLevelID + 1)
                //<< (quint32)wordCount
                << QString("");
            emit s_SendCodeDataToServer(m_pGameSocket,ba);
            if(saveClassLevel(m_pWordLib->m_nClassID, m_pWordLib->m_nLevelID + 1, "") == false)
                return false;
            /*
            m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST
                                        << (qint16)GAME_SERVER_SAVESTUDYINFO
                                        //<< userGameID()
                                        << (quint32)m_pWordLib->m_nClassID
                                        << (quint32)(m_pWordLib->m_nLevelID + 1)
                                        << (quint32)wordCount
                                        << QString("")
                                        << true;
            m_pGameSocket->send();
            */
        }
    }
    /*
    qDebug()<<"测试："<<m_pWordLib->unStudiedCount()
           <<pCInfo->m_mapLevel.count()
          <<m_pWordLib->m_nLevelID
         <<m_pWordLib->getWordCount(m_pWordLib->m_nClassID, m_pWordLib->m_nLevelID + 1);*/

    emit s_RefreshAllLevels();
    return true;
}

bool UserInfo::saveClassLevel(int classID, int levelID, QString result)
{
    //检测classID
    if(!m_StudyInfo.m_mapClassInfo.contains(QString::number(classID)))
    {
        qCritical()<<"[!UserInfo]不存在的ClassID:"<<classID;
        return false;
    }

    //如果不包含LevelID,则插入
    if(!m_StudyInfo.m_mapClassInfo.value(QString::number(classID)).value<ClassInfo*>()->m_mapLevel.contains(QString::number(levelID)))
    {
        LevelInfo *pLevel = new LevelInfo;
        pLevel->m_nClassID = classID;
        pLevel->m_nLevelID = levelID;
        pLevel->m_unWordCount = m_pWordLib->getWordCount(classID, levelID);
        //pLevel->m_CorrectCount = query.value("CorrectCount").toInt();
        //pLevel->m_MistakeCount = query.value("MistakeCount").toInt();
        pLevel->m_strWordRecords = result;   //!!!注意这里
        m_StudyInfo.m_mapClassInfo.value(QString::number(classID)).value<ClassInfo*>()->m_mapLevel.insert(QString::number(levelID), QVariant::fromValue(pLevel));
        qDebug()<<"[GameManager]INSERT"<<m_StudyInfo.m_mapClassInfo.value(QString::number(classID)).value<ClassInfo*>()->classID();
    }
    else
    {
        //((LevelInfo*)(pUserInfo->m_StudyInfo.m_mapClassInfo.value(QString("%1").arg(classID)).value<ClassInfo*>()->m_mapLevel.value(QString(levelID))))->m_strWordRecords = result;
        m_StudyInfo.m_mapClassInfo.value(QString::number(classID)).value<ClassInfo*>()->m_mapLevel.value(QString::number(levelID)).value<LevelInfo*>()->m_strWordRecords = result;
        qDebug()<<"[GameManager]UPDATE"<<m_StudyInfo.m_mapClassInfo.value(QString::number(classID)).value<ClassInfo*>()->classID();
    }
    return true;
}

bool UserInfo::updateGameUserScoreInfo()
{
    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out<<(qint16)GAME_SERVER_REQUEST
      <<(qint16)GAME_SERVER_UPDATESCORE
     //<<userGameID()
    <<m_GameServerUserInfo.nScoreAdd;
    emit s_SendCodeDataToServer(m_pGameSocket,ba);

    setScoreCount(scoreCount() + m_GameServerUserInfo.nScoreAdd);

    return true;
}

bool UserInfo::sl_qml_UserLogin(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    if(pInfo["userName"].toString().isEmpty()
            || pInfo["password"].toString().isEmpty())
        return false;
    setUserName(pInfo["userName"].toString());
    m_LoginInfo.m_strPassword = pInfo["password"].toString();
    m_LoginInfo.m_ClientStatus = Client_IsLoginingInfoServer;



    m_pInfoSocket->connectServer();
    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    QString authcode = "nEv7NeFNCceFjZdSjl";  //密码的盐
    QByteArray passMD5 = QCryptographicHash::hash ( (authcode + m_LoginInfo.m_strPassword).toLatin1(), QCryptographicHash::Md5 );
    passMD5 = QCryptographicHash::hash ( passMD5.toHex(), QCryptographicHash::Md5 );

    authcode = "###" + QString::fromLatin1(passMD5.toHex());
    //qDebug() << authcode;

    /*
    m_pInfoSocket->sendData(0x10) << (qint16)INFO_SERVER_REQUEST<<(qint16)INFO_SERVER_LOGIN
                                << userName()
                                << m_LoginInfo.m_strPassword;
    m_pInfoSocket->send();*/

    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)INFO_SERVER_REQUEST<<(qint16)INFO_SERVER_LOGIN
        << userName()
        << authcode;
    emit s_SendCodeDataToServer(m_pInfoSocket,ba);

    return true;
}

bool UserInfo::sl_qml_UserReg(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    if(pInfo["userName"].toString().isEmpty()
            || pInfo["password"].toString().isEmpty())
        return false;

    setUserName(pInfo["userName"].toString());
    m_LoginInfo.m_strPassword = pInfo["password"].toString();
    //setNickName(pInfo["nickName"].toString());
    //setSex(pInfo["sex"].toInt());

    m_LoginInfo.m_ClientStatus = UserInfo::Client_IsRegisteringInfoServer;
    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    /*
    m_pInfoSocket->sendData(0x10) << (qint16)INFO_SERVER_REQUEST<<(qint16)INFO_SERVER_REGISTER
                                << userName()
                                << nickName()
                                << m_LoginInfo.m_strPassword
                                << sex();
    m_pInfoSocket->send();*/
    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)INFO_SERVER_REQUEST<<(qint16)INFO_SERVER_REGISTER
        << userName()
        << nickName()
        << m_LoginInfo.m_strPassword
        << sex();
    emit s_SendCodeDataToServer(m_pInfoSocket,ba);

    return true;
}

bool UserInfo::sl_qml_GameUserReg(QVariant param)
{
    QMap<QString,QVariant> pInfo = param.toMap();

    QString nick = pInfo["nickName"].toString();

    int nicklength = nick.length() + nonASCIICount(nick);
    if(nicklength < 4 || nicklength > 16)
    {
        emit s_regGameStatus(2);
        return false;
    }
    if(checkBadWord(nick) == false)
    {
        emit s_regGameStatus(3);
        return false;
    }

    setNickName(pInfo["nickName"].toString());
    setSex(pInfo["sex"].toInt());
    setScoreCount(0);
    m_GameServerUserInfo.nScoreYesterday = 0;
    m_GameServerUserInfo.nScoreWeek = 0;

    m_LoginInfo.m_ClientStatus = Client_IsRegisteringGameServer;
    //sendUserInfoToServer();
    //qDebug()<<pInfo;
    //sendUserInfoToLocalTest();

    /*m_pGameSocket->sendData(0x10) << (qint16)GAME_SERVER_REQUEST<<(qint16)GAME_SERVER_REGISTERGAMEUSERINFO
                                  << m_LoginInfo.id
                                  << serverID()
                                  << nickName()
                                  << sex();
    m_pGameSocket->send();*/

    QByteArray ba;
    QDataStream out(&ba,QIODevice::WriteOnly);
    out << (qint16)GAME_SERVER_REQUEST<<(qint16)GAME_SERVER_REGISTERGAMEUSERINFO
        << m_LoginInfo.m_unID
        << serverID()
        << nickName()
        << sex();
    emit s_SendCodeDataToServer(m_pGameSocket,ba);

    return true;
}


bool UserInfo::sendUserInfoToLocalTest()
{
    if(m_pTempDB == nullptr)return false;
    if (!m_pTempDB->isValid() || !m_pTempDB->isOpen())
        return false;

    QString sql;
    QSqlQuery query(*m_pTempDB);  //查询


    switch(m_LoginInfo.m_ClientStatus)
    {
    case Client_IsLoginingInfoServer:
        {
            sql = QString("SELECT * FROM UserInfo WHERE username='%1'").arg(userName());
            if(!query.exec(sql))
            {
                Critical("Query UserInfo Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                emit s_loginStatus(-1);
                return false;
            }
            if(query.next())        //if(query.seek(0) == false)
            {
                if(m_LoginInfo.m_strPassword == query.value("password").toString())
                {
                    m_LoginInfo.m_unID = query.value("id").toInt();
                    //setUserName(query.value("username").toString());
                    //setNickName(query.value("nickname").toString());
                    m_LoginInfo.m_strPassword = query.value("password").toString();
                    //setSex(query.value("sex").toInt());
                    query.finish();

                    //loadGameServersInfo();
                    m_LoginInfo.m_ClientStatus =  Client_IsLoginedInfoServer;
                    emit s_loginStatus(0);
                    return true;
                }
                else
                {
                    query.finish();
                    emit s_loginStatus(1);
                    return true;
                }
            }
            else
            {
                query.finish();
                emit s_loginStatus(2);
                return true;
            }
        }
        break;
    case Client_IsRegisteringInfoServer:
        {
            //查询用户Record
            sql = QString("SELECT id FROM UserInfo WHERE username='%1' LIMIT 1").arg(userName());
            if(!query.exec(sql))
            {
                Critical("SELECT UserInfo Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                emit s_regStatus(-1);
                return false;
            }
            if(query.next())
            {
                query.finish();
                emit s_regStatus(1);
                return true;
            }
            query.finish();


            //插入用户信息
            sql = QString("INSERT INTO UserInfo(username,nickname,password,sex) VALUES('%1','%2','%3',%4)").arg(userName()).arg(nickName()).arg(m_LoginInfo.m_strPassword).arg(sex());
            if(!query.exec(sql))
            {
                Critical("INSERT UserInfo Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                emit s_regStatus(-2);
                return false;
            }
            query.finish();

            m_LoginInfo.m_ClientStatus = Client_IsLoginedInfoServer;
            emit s_regStatus(0);
            return true;
        }
        break;
    case Client_IsRegisteringGameServer:
        {
            if(checkBadWord(nickName()) == false)
            {
                emit s_regGameStatus(2);
                return true;
            }

            //查询昵称Record
            sql = QString("SELECT ID FROM GameUserInfo WHERE NickName='%1' LIMIT 1").arg(nickName());
            if(!query.exec(sql))
            {
                Critical("SELECT GameUserInfo Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                return false;
            }
            if(query.next())
            {
                query.finish();
                emit s_regGameStatus(1);
                return true;
            }
            query.finish();



            //添加昵称Record
            sql = QString("INSERT INTO GameUserInfo(userid,serverid,NickName,Sex,Score) VALUES(%1,%2,'%3',%4,0)").arg(m_LoginInfo.m_unID).arg(serverID()).arg(nickName()).arg(sex());
            if(!query.exec(sql))
            {
                Critical("insert GameUserInfo Error");
                Critical(m_pWordLib->getDB()->lastError().text());
                Critical(query.lastError().text());
                Critical(sql);
                query.finish();
                return false;
            }
            query.finish();
            setScoreCount(0);

/*
            //添加经验Record
            sql = QString("INSERT INTO GameUserScoreInfo(usergameid,score) VALUES(%1,0)").arg(m_LoginInfo.id);
            if(!query.exec(sql))
            {
                Critical("insert GameUserScoreInfo Error");
                query.finish();
                return -1;
            }
            query.finish();*/

            loadGameUserInfoLocal();
            m_LoginInfo.m_ClientStatus =  Client_IsLoginedGameServer;
            emit s_choiceGameServerStatus(1);
            return true;
        }
        break;
    case Client_IsLoginingGameServer:
        {
        }
        break;
    default:
        ;
    }
    return false;
}


QVariantMap UserInfo::sl_getUserLevelInfo(int score)
{
    QVariantMap info;
    if(!m_pWordLib->isValid())
        return info;

    QString sql = QString("SELECT * FROM LevelInfo WHere %1>=Score ORDER By Score DESC Limit 1")
            .arg(score);
    QSqlQuery query(*m_pWordLib->getDB());  //查询
    if(!query.exec(sql))
    {
        qCritical() << (m_pWordLib->getDB()->lastError().text());
        qCritical() << (query.lastError().text());
        qCritical() << (sql);
        query.finish();
        return info;
    }
    if(query.next())
    {
        info.insert("level", query.value("ID"));
        info.insert("name", query.value("Name"));
        info.insert("Score", query.value("Score"));
    }
    else
    {
        info.insert("level", 0);
        info.insert("name", "无");
        info.insert("Score", 0);
    }

    query.finish();
    return info;
}
